package assets
{
	import away3d.textures.ATFCubeTexture;
	import away3d.textures.ATFTexture;
	
	import com.riaidea.utils.zip.ZipArchive;
	import com.riaidea.utils.zip.ZipEvent;
	import com.riaidea.utils.zip.ZipFile;
	
	import events.LoadedEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	
	/**
	 * 一些服务器对提供下载的文件类型作了很多限制，于是便把atf贴图资源压缩到一个对应的zip文件中作为下载资源
	 */	
	public class AssetAtfTextureWhitZIP extends EventDispatcher
	{
		private var loadingList:Array = new Array;
		private var currentLoadingURL:String;
		private var loader:ZipArchive;
		
		private var _isCubeLIst:Array = new Array;
		private var _isCube:Boolean;
		
		public function AssetAtfTextureWhitZIP()
		{
			loader = new ZipArchive;
			loader.addEventListener(ZipEvent.ERROR,onError);
		}
		
		private function onError(e:ZipEvent):void
		{
			var errorInfo:String ="ZIP资源异常："+ currentLoadingURL;
			throw new Error(errorInfo);
		}
		
		public function load(URL:String,isCubeTexture:Boolean = false):void
		{
			if(loadingList.indexOf(URL) > -1)return;
			
			if(Asset.resBitmapDatas[URL] == undefined)
			{
				loadingList.push(URL);
				_isCubeLIst.push(isCubeTexture);
				
				if(loadingList.length==1)loadNext();
				
			}else{
				dispatchEvent(new LoadedEvent(URL,LoadedEvent.TEXTURE_COMPLETE));
			}
		}
		
		///////////////////////////////////////////////
		private function loadNext():void
		{
			currentLoadingURL = loadingList[0];
			_isCube = _isCubeLIst[0];
			loader.addEventListener(ZipEvent.INIT,onloadComplete);
			
			loader.load(currentLoadingURL);
		}
		
		private function onloadComplete(e:Event):void
		{
			var strs:Array = currentLoadingURL.split(/\.|\/|\\/);
			var atfName:String = strs[strs.length-2]+".atf";
			
			var xmlFile:ZipFile = loader.getFileByName(atfName);
			if(!_isCube)
			{
				var _texture:ATFTexture = new ATFTexture(xmlFile.data); 
				Asset.resAtfTextures[currentLoadingURL] = _texture;
			}else
			{
				var _cubeTexture:ATFCubeTexture = new ATFCubeTexture(xmlFile.data); 
				Asset.resAtfTextures[currentLoadingURL] = _cubeTexture;
			}
			
			loadingList.splice(0,1);
			_isCubeLIst.splice(0,1);
			
			dispatchEvent(new LoadedEvent(currentLoadingURL,LoadedEvent.TEXTURE_COMPLETE));
			
			if(loadingList.length == 0)
			{
				loader.removeEventListener(Event.COMPLETE,onloadComplete);
				return;
			}
			
			loadNext();
		}
	}
}